package org.dragon.models;

import org.dragon.commons.Const;
import org.dragon.commons.Times;
import org.springframework.util.StringUtils;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * Author:     Zhao Yan
 * DateTime:   2023/5/18 9:03
 */
public class RedisSessionEmail {

    private String email;

    private Long lastSentTime;

    private String code;

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Long getLastSentTime() {
        return lastSentTime;
    }

    public void setLastSentTime(Long lastSentTime) {
        this.lastSentTime = lastSentTime;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public boolean canSendCode() {
        // 验证发送间隔
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime last = Times.toLocalDateTime(lastSentTime);
        LocalDateTime expired = last.plus(Duration.ofSeconds(Const.EMAIL_CODE_SEND_INTERVAL));

        return now.isAfter(expired);
    }

    public boolean validate(String code) {
        return StringUtils.hasText(code) && Objects.equals(this.code, code);
    }

    @Override
    public String toString() {
        return "RedisSessionEmail{" +
                "email='" + email + '\'' +
                ", lastSentTime=" + lastSentTime +
                ", code='" + code + '\'' +
                '}';
    }
}
